package com.share.tool.devops.controller;

import com.alibaba.fastjson.JSON;
import com.share.common.logback.IpProperty;
import com.share.common.utils.StrUtil;
import com.share.tool.devops.model.po.SerRegister;
import com.share.tool.devops.service.SerRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监听待添加
 */
@Slf4j
@RestController
public class RefreshController {
    //当前服务的本地变量
    String ip;
    String contextPath;
    String port;
    String serviceName;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private Environment environment;

    @Autowired
    private SerRegisterService serRegisterService;

    @PostConstruct
    public void init() {
        //1.设置所有的机器ip到数据库中存着
        ip = new IpProperty().getPropertyValue();
        contextPath = StrUtil.getValue(environment.getProperty("server.servlet.context-path"), "/");
        port = StrUtil.getValue(environment.getProperty("server.port"), "8080");
        serviceName = environment.getProperty("spring.application.name");
        log.info("正在初始化ip={},contextPath={},port={},serviceName={}，", ip, contextPath, port, serviceName);

        //2.初始化具体的类
        boolean bool = serRegisterService.registerAndClearHistory(ip, contextPath, port, serviceName);/*这里不管下线的机器*/
        log.info("当前机器注册bool={}", bool);

        Object initValue = null;

        //3.其他的服务注册
        initValue = serRegisterService.init();
        log.info("初始化的serRegisterService={}", JSON.toJSON(initValue));
    }


    /**
     * 通用刷新接口------通过方法不要修改
     *
     * @param code    service实现类的名字，通过这个名字执行反射
     * @param version 只刷当前机器则需要传递
     * @return
     */
    @RequestMapping("/refresh/{code}")
    public Object refresh(@PathVariable("code") String code, Long version) {
        Map<String, Object> resultMap = new HashMap<>();

        //参数校验
        Object bean = null;
        Method method = null;
        try {
            bean = applicationContext.getBean(code);
            method = bean.getClass().getMethod("init");
        } catch (Exception e) {
            log.error("入参code={}值不存在与容器中,或者无init方法", code, e);
        }
        if (bean == null || method == null) {
            return "参数异常,无法识别code=" + code;
        }

        //递归调用
        if (version == null) {/*执行循环*/
            List<SerRegister> list = serRegisterService.listService(serviceName, port, contextPath);
            version = System.currentTimeMillis();//生成一个版本
            for (SerRegister ser : list) {
                String reqUrl = String.format("http://%s:%s/%s/refresh/%s?version=%d", ser.getIp(), ser.getPort(), ser.getContextPath(), code, version);
                log.info("正在刷新服务reqUrl={}", reqUrl);
                Map body = new RestTemplate().postForEntity(reqUrl, null, Map.class).getBody();
                resultMap.putAll(body);
            }
        } else { /*调用具体的方法*/
            Object value = null;
            try {
                value = method.invoke(bean);
                String key = ip + "_" + port + "_" + contextPath + "_" + serviceName + "_" + code;
                resultMap.put(key, value);

                serRegisterService.updateVersion(version, ip, port, serviceName, contextPath);
            } catch (Exception e) {
                log.error("加载异常", e);
            }
        }
        return resultMap;
    }
}
